package filestore

import (
	"app-box/config"
	"errors"
	"fmt"
	"path/filepath"
	"regexp"
	"strings"
	"time"
)

// 将临时文件夹内的文件保存到永久文件夹
func (fileStr *FileString) SaveTempFiles() {
	*fileStr = fileStr.ReplaceKeysForEtch(func(key FileKey) FileKey {
		if strings.HasPrefix(key.ObjectKey, "/tmp/") {
			saveKey, success := keyFromTmpKey(key.ObjectKey)
			if success {
				switch key.Type {
				case FileKeyTypeLocal:
					localStore.Copy(key.ObjectKey, saveKey)
				case FileKeyTypeQiNiu:
					// 七牛 todo
				}
			}
			return FileKey{key.Type, saveKey}
		}
		return key
	})
}

// 永久删除字符串中包含的所有文件
func (fileStr FileString) DeleteFiles() {
	var keys = fileStr.GetKeys()
	for _, key := range keys {
		if key.Type == FileKeyTypeLocal {
			localStore.Delete(key.ObjectKey)
		} else {
			/// TODO: 七牛云
		}
	}
}

// 删除已经不存在的文件
func (newStr *FileString) DeleteOldFiles(oldStr FileString) {
	var newKeys = newStr.GetKeys()
	var oldKeys = oldStr.GetKeys()
	var deleteMap = make(map[string]FileKey)
	for _, item := range oldKeys {
		deleteMap[item.Type+item.ObjectKey] = item
	}
	for _, item := range newKeys {
		if _, ok := deleteMap[item.Type+item.ObjectKey]; ok {
			delete(deleteMap, item.Type+item.ObjectKey)
		}
	}
	deleteLocalKeys := make([]string, 0)
	deleteQiniuKeys := make([]string, 0)

	for _, fileKey := range deleteMap {
		switch fileKey.Type {
		case FileKeyTypeQiNiu:
			deleteQiniuKeys = append(deleteQiniuKeys, fileKey.ObjectKey)
		case FileKeyTypeLocal:
			deleteLocalKeys = append(deleteLocalKeys, fileKey.ObjectKey)
		}
	}
	newStr.SaveTempFiles()
	if len(deleteLocalKeys) != 0 {
		localStore.Delete(deleteLocalKeys...)
	}
	if len(deleteQiniuKeys) != 0 {
		// TODO: 七牛
	}

}

func UploadString(str, key string) FileString {
	if config.Server.FileUploadType == config.FileUploadTypeLocal {
		return localStore.UploadString(str, key)
	} else if config.Server.FileUploadType == config.FileUploadTypeLocal {
		// TODO: 七牛
	}
	panic(errors.New("不支持的文件上传方式"))
}

func CreateTmpKey(userID, fileType, key string) FileKey {
	var dateNow = time.Now()
	dateStr := dateNow.Format("2006-01-02")
	newKey := fmt.Sprintf("/tmp/%s/%s/", dateStr, userID)
	newKey = filepath.Join(newKey, key)
	return FileKey{
		Type:      fileType,
		ObjectKey: newKey,
	}
}

func keyFromTmpKey(tmpKey string) (key string, success bool) {
	reg, err := regexp.Compile(`/tmp/\d{4}-\d{2}-\d{2}(/[a-zA-Z0-9]+/.+)`)
	if err != nil {
		return
	}
	matchs := reg.FindStringSubmatch(tmpKey)
	if len(matchs) == 0 {
		return
	}
	key = matchs[1]
	success = true
	return
}
